//获取应用实例
var app = getApp();
var appId = require('../../config').appId;
var config = require('../../config');
const $ = require('../../utils/utils');
const errorCode = require('../../utils/errorCode');
const version = config.appversion;
const user = require('../../manager/userManager')

Page({

    /**
       * 页面的初始数据
       */
    data: {
        userPhone: "",
        isTime: 1,
        rest_count: 60,
        version_data: version,
        path: "",
        scanCode: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(`#login_onload()  ${JSON.stringify(options)}`);
        if (options.path) {
            this.setData({
                path: options.path,
                scanCode: options.scanCode
            });
        }
        if (options.q) {
            var src = decodeURIComponent(options.q);
            console.warn(src);
            var visitorId = app.getQueryStringArgs(src);
            console.warn('visitorId:' + visitorId.visitorId);
            if (visitorId.visitorId) {
                wx.setStorageSync('visitorId', visitorId.visitorId);
            }
        } else {
            if (wx.getStorageSync('visitorId')) wx.removeStorageSync('visitorId');
        }

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (options) {
        // user.getUserInfo()
        $.showLoading("正在尝试自动登录...")
        user.checkWXSession().then(data => {
            if (wx.getStorageSync("isLogin")) {
                wx.reLaunch({
                    url: config.page.index,
                })
            }
        }).catch(error => {
            $.hideLoading()
            $.showToast("自动登录失败，请手动登录")
        })
    },


    /******************Methods ****************/
    bindKeyInput: function (e) {
        this.setData({
            userPhone: e.detail.value
        });
    },

    time_down: function () {
        var that = this;
        var second = 60;
        var timer = null;
        timer = setInterval(function () {
            second -= 1;
            if (second > 0) {
                that.setData({
                    rest_count: second
                });
            } else {
                clearInterval(timer);
                that.setData({
                    isTime: 1
                });
            }
        }, 1000);
    },


    getTestCode: function () {

        var that = this;
        if (that.data.userPhone == "") {
            $.showToast('请填写手机号码!')
        } else if (that.data.userPhone.length != 11) {
            $.showToast('请输入11位手机号!')
        } else {
            let data = {
                mobile_no: that.data.userPhone
            }
            let url = $.getUrl(config.getRegisterCode, data)
            $.get(url).then(data => {
                if (data.code !== errorCode.SMS_SEND_SUCCESS) {
                    // 短信发送不成功时，才提示错误信息
                    $.alert(data.message)
                } else {
                    // 成功时才倒计时
                    that.setData({
                        rest_count: 60,
                        isTime: 0
                    });
                    that.time_down();
                }
            })
        }
    },

    formSubmit: function (e) {
        console.log("#login_formSubmit")
        var that = this;
        if (!e.detail.value.user_code) {
            $.showToast("验证码不得为空")
        } else { 
            that.loginAction(e)
        }
    },

    loginAction: function (e){
        var that = this;
        wx.showLoading({
            title: "正在登录...",
            mask: true,
            success: function () {
                let data = {
                    mobile_no: e.detail.value.user_phone,
                    verify_code: e.detail.value.user_code,
                    visitorId: wx.getStorageSync('visitorId'),
                    usertoken: wx.getStorageSync("usertoken")
                }
                let url = config.phoneLogin
                $.post(url, data).then(data => {
                    if (data.code != 0) {
                        $.showToast(data.message)
                        return
                    }
                    // 保存用户登录数据
                    user.saveLoginInfo(data.detail)
                    wx.setStorageSync("userPhone", e.detail.value.user_phone)

                    if (data.result != 1) {
                        $.showToast(data.message)
                    } else {
                        //成功登陆，接口返回
                        wx.hideToast();
                        if (that.data.path == "activity") {
                            $.goto(config.page.getMonthCard, true)
                            return
                        } else if (that.data.path == 'attendorInfo') {//助力进来的
                            app.saveAttendorInfo();
                        }
                        
                        if (that.data.path == 'weekRank') {
                            wx.navigateBack({
                            })
                        }

                        if (that.data.path == "scanCode") {
                            wx.setStorageSync("scanIsFromLogin", true)
                            app.scanCode()
                        }

                        if (that.data.path !== "activity" && that.data.path !== 'attendorInfo') {
                            wx.navigateBack({
                            })
                        }

                    }
                }).catch(error => {
                    $.showToast(error.message)
                });

            }

        });
    },

    despoit_webview: function () {
        app.globalData.webview = {
            url: config.licenseUrl,
            title: '用户协议'
        };
        $.goto(config.page.webview);
    },


})